package com.chengzzz.mysite.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.chengzzz.mysite.entity.Animation;
import com.chengzzz.mysite.entity.User;
import com.chengzzz.mysite.enums.ResultEnum;
import com.chengzzz.mysite.pojo.UserPojo;
import com.chengzzz.mysite.result.Result;
import com.chengzzz.mysite.service.AnimationService;
import com.chengzzz.mysite.service.UserService;
import com.chengzzz.mysite.utils.JWTUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.sql.Array;
import java.util.*;

/**
 * <p>
 * 访问控制器
 * </p>
 *
 * @author 等什么柠檬君
 * @since 2020/8/24
 */

@RestController
@CrossOrigin
@RequestMapping(value = "Service")
public class AccessController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserService userService;

    @Autowired
    private AnimationService animationService;


    /**
     * @param user user
     * @return com.chengzzz.mysite.result.Result<java.lang.Object>
     * @author 等什么柠檬君
     * @description 用户基本权限
     * @since 2020/8/25
     */
    @ApiOperation("用户登录的接口，返回Token")
    @RequestMapping(value = "/Login", method = RequestMethod.POST)
    public Result<Object> login(@RequestBody @ApiParam("传入用户实体类中的邮箱 密码 登录ip 现行时间戳") User user) {
        logger.info(user.toString());


        Subject subject = SecurityUtils.getSubject();
        user.setLoginip("111111");
        user.setTimesamp("1111111");
        UsernamePasswordToken tokenShiro = new UsernamePasswordToken(user.getEmail(), user.getPassword());
        UserPojo userPojo = new UserPojo(user.getEmail(), user.getPassword(), user.getLoginip(), user.getTimesamp());
        logger.info(userPojo.toString());
        System.out.println("shiro开始登录");
        try {
            subject.login(tokenShiro);
            System.out.println("shiro登录完成");
            User userDB = (User) subject.getPrincipal();
            System.out.println(userDB.toString());

          if (!user.getEmail().equals(userDB.getEmail())){
                 return new Result(ResultEnum.ACCOUNT_ERROR.getCode(), "滚你妈的你在逗我？", null, false);
          }
            //  User userDB = userService.userIdentValidation(user);
            Map<String, String> payload = new HashMap<>();
            payload.put("eamil", userDB.getEmail());
            payload.put("password", userDB.getPassword());
            payload.put("username", userDB.getUsername());
            String token = JWTUtils.getToken(payload);

            if (!userDB.getRegisteip().equals(userPojo.getLoginip())) {
                return new Result(ResultEnum.LOGIN_SUCCESS.getCode(), "登陆成功,您当前的ip非注册ip可能存在风险", token, true);
            } else {
                return new Result(ResultEnum.LOGIN_SUCCESS.getCode(), "登陆成功。欢迎，" + userDB.getUsername(), token, true);
            }

        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return new Result(ResultEnum.ACCOUNT_ERROR.getCode(), "登陆失败,请检查你的账号", null, false);
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return new Result(ResultEnum.PASSWORD_ERROE.getCode(), "登陆失败,请检查你的密码", null, false);
        }


//        if (null == user.getEmail() || null == user.getPassword() || null == user.getLoginip() || null == user.getTimesamp()) {
//            return new Result(ResultEnum.ERROR.getCode(), "参数错误");
//        } else {
//            UserPojo userPojo = new UserPojo(user.getEmail(), user.getPassword(), user.getLoginip(), user.getTimesamp());
//            logger.info(userPojo.toString());
//            User userDB = userService.userIdentValidation(user);
//
//            if (null != userDB) {
//                logger.info(userDB.toString());
//                try {
//                    Map<String, String> payload = new HashMap<>();
//                    payload.put("eamil", userDB.getEmail());
//                    payload.put("password", userDB.getPassword());
//                    payload.put("username", userDB.getUsername());
//                    String token = JWTUtils.getToken(payload);
//                    if (!userDB.getRegisteip().equals(userPojo.getLoginip())) {
//                        return new Result(ResultEnum.LOGIN_SUCCESS.getCode(), "登陆成功,您当前的ip非注册ip可能存在风险", token, true);
//                    } else {
//                        return new Result(ResultEnum.LOGIN_SUCCESS.getCode(), "登陆成功。欢迎，" + userDB.getUsername(), token, true);
//                    }
//                } catch (Exception e) {
//                    return new Result(ResultEnum.ERROR.getCode(), e.getMessage(), null, false);
//                }
//
//            } else {
//
//                return new Result(ResultEnum.PASSWORD_ERROE.getCode(), "登陆失败,请检查你的账号及密码", null, false);
//            }
//        }

    }

    @ApiOperation("用户注册的接口")
    @RequestMapping(value = "/Regist", method = RequestMethod.POST)
    public Result Regist(@RequestBody @ApiParam("传入用户实体类中的邮箱 密码 注册ip 现行时间戳") User user) {
        return userService.UserRegist(new User(user.getEmail(), user.getPassword(), user.getRegisteip()));
    }


    @ApiOperation("无权限")
    @RequestMapping(value = "/unauth", method = RequestMethod.GET)
    public Result unauth() {
        return new Result(ResultEnum.PASSWORD_ERROE.getCode(), "您他妈的没有权限", null, false);
    }

    @ApiOperation("未登录")
    @RequestMapping(value = "/unlogin", method = RequestMethod.GET)
    public Result unlogin() {
        return new Result(ResultEnum.PASSWORD_ERROE.getCode(), "您他妈的没有登录", null, false);
    }



    @ApiOperation("拿用户信息的接口")
    @RequestMapping(value = "/getPersonInfo", method = RequestMethod.POST)
    public Result getPersonInfo(@RequestParam @ApiParam("email") String email) {
//        User userDB =  userService.findUserByEmail(user.getEmail());
        System.out.println("拿用户信息的接口");
            User userDB =  userService.findUserByEmail(email);
            return new Result(ResultEnum.SUCCESS.getCode(), "查询成功", userDB, true);


    }
    @ApiOperation("拿用户信息的接口")
    @RequestMapping(value = "/getPersonInfoByToken", method = RequestMethod.GET)
    public Result getPersonInfoByToken(@RequestParam @ApiParam("传入token") String token) {
//        User userDB =  userService.findUserByEmail(user.getEmail());
        System.out.println(token);
        System.out.println("拿用户信息的接口token");
       List a= Arrays.asList(StringUtils.split(token,"."));
        System.out.println(a.get(1));
        try {
           String email = JWTUtils.returnEmail(a.get(1).toString());
            User userDB =  userService.findUserByEmail(email);
            return new Result(ResultEnum.SUCCESS.getCode(), "查询成功", userDB, true);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return new Result(ResultEnum.ERROR.getCode(), "查询失败", false, true);
        }
    }




    /**
     * @param
     * @return com.chengzzz.mysite.result.Result
     * @author 等什么柠檬君
     * @description 管理员权限
     * @since 2020/8/25
     */
    @ApiOperation("管理员创建用户的接口，请求头需携带Token")
    @RequestMapping(value = "/Admin/insertUser", method = RequestMethod.POST)
    public Result insertUser(@RequestBody @ApiParam("保证邮箱密码不为空即可") User user) {
        logger.info(user.toString());
       // return userService.insertUser(new User(user.getEmail(), user.getPassword(), user.getRegisteip()));
        return userService.insertUser(user);
    }

    @ApiOperation("管理员删除用户的接口，请求头需携带Token")
    @RequestMapping(value = "/Admin/deleteUser", method = RequestMethod.GET)
    public Result DeleteUser(@RequestParam @ApiParam("传入唯一id") Long uuid) {
        return userService.UserDelete(uuid);
    }

    @ApiOperation("管理员更新用户的接口，请求头需携带Token")
    @RequestMapping(value = "/Admin/UpdateUser", method = RequestMethod.POST)
    public Result UpdateUser(@RequestBody User user) {
        return userService.UserUpdate(user);
    }

    @ApiOperation("管理员获取所有用户的接口，请求头需携带Token")
    @RequestMapping(value = "/Admin/getAllUser", method = RequestMethod.GET)
    public Result ListAllUser(@RequestParam Integer page, @RequestParam Integer limit) {
        if (null == page || null == limit) {
            return new Result(ResultEnum.ERROR.getCode(), "登陆失败,请检查你的账号及密码", null, false);
        }
        return new Result(ResultEnum.SUCCESS.getCode(), "查询成功", userService.ListAllUser(page, limit), true);
    }
    @ApiOperation("管理员新建番剧的接口，请求头需携带Token")
    @RequestMapping(value = "/Admin/insertAnimation", method = RequestMethod.POST)
    public Result insertAnimation(@RequestBody Animation animation) {
        return animationService.insertAnimation(animation);
    }

    @ApiOperation("管理员删除番剧的接口，请求头需携带Token")
    @RequestMapping(value = "/Admin/deleteAnimation", method = RequestMethod.GET)
    public Result DeleteAnimation(@RequestParam Long uuid) {
        return animationService.AnimationDelete(uuid);
    }

    @ApiOperation("管理员更新番剧的接口，请求头需携带Token")
    @RequestMapping(value = "/Admin/UpdateAnimation", method = RequestMethod.POST)
    public Result UpdateAnimation(@RequestBody Animation animation) {
        if (animation != null) {
            return animationService.AnimationUpdate(animation);
        }
        return new Result(ResultEnum.ERROR.getCode(), "参数错误", null, false);
    }


    /**
     * @return java.util.List
     * @author 等什么柠檬君
     * @description 公共权限
     * @since 2020/8/25
     */

    @ApiOperation("注册用户获取所有番剧的接口，请求头需携带Token")
    @RequestMapping(value = "/getAnimationList", method = RequestMethod.POST)
    public Result getAnimationList() {
        return new Result(ResultEnum.SUCCESS.getCode(), "查询成功", animationService.selectAS(), false);
    }

    @ApiOperation("注册用户获取所有番剧的分页接口，请求头需携带Token")
    @RequestMapping(value = "/Interaction/getAnimationPage", method = RequestMethod.GET)
    public Result getPage(@RequestParam Integer page, @RequestParam Integer limit) {
        System.out.println(page+"   "+limit);
        if (null == page || null == limit) {
           return new Result(ResultEnum.ERROR.getCode(), "参数非法", false, false);
        }
        return new Result(ResultEnum.SUCCESS.getCode(), "查询成功", animationService.selectByPage(page, limit), false);

    }

    @ApiOperation("测试接口，请求头无需携带Token")
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public Result<Object> test() {
        return new Result(ResultEnum.ERROR.getCode(), "如果你看到这个页面。表明后端已准备就绪");
    }

    @ApiOperation("测试接口，请求头需携带Token")
    @RequestMapping(value = "/Interaction/test", method = RequestMethod.GET)
    public Result<Object> login() {
        return new Result(ResultEnum.ERROR.getCode(), "如果你看到这个页面已经通过过滤器的token验证");
    }
}
